<template>
  <el-dialog
    v-model="visible"
    title="数据迁移"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="!migrating"
    center
  >
    <!-- 迁移前提示 -->
    <div v-if="!migrating && !migrationCompleted" class="migration-prompt">
      <div class="icon-container">
        <el-icon :size="48" color="#409EFF">
          <Upload />
        </el-icon>
      </div>
      <h3>检测到本地数据</h3>
      <p class="description">
        我们在您的浏览器中发现了 <strong>{{ dataCount }}</strong> 个智能体数据。
        为了更好的体验，建议将这些数据迁移到服务器。
      </p>
      <div class="benefits">
        <h4>迁移后的优势：</h4>
        <ul>
          <li>数据云端同步，不会丢失</li>
          <li>多设备访问，随时随地使用</li>
          <li>更好的性能和稳定性</li>
        </ul>
      </div>
    </div>

    <!-- 迁移进行中 -->
    <div v-if="migrating || isValidating" class="migration-progress">
      <div class="icon-container">
        <el-icon :size="48" color="#409EFF" class="rotating">
          <Loading />
        </el-icon>
      </div>
      <h3 v-if="migrating">正在迁移数据...</h3>
      <h3 v-else-if="isValidating">正在验证数据...</h3>
      <p class="current-item">{{ currentMigrationItem }}</p>
      
      <el-progress
        :percentage="isValidating ? 90 : migrationPercentage"
        :stroke-width="8"
        :status="isValidating ? 'warning' : 'success'"
        :show-text="true"
      />
      
      <div class="progress-info">
        <span v-if="migrating">{{ migratedCount }} / {{ totalCount }}</span>
        <span v-if="isValidating">正在验证数据完整性...</span>
      </div>
    </div>

    <!-- 迁移完成 -->
    <div v-if="migrationCompleted" class="migration-result">
      <div class="icon-container">
        <el-icon 
          :size="48" 
          :color="migrationResult.success && validationErrors.length === 0 ? '#67C23A' : '#F56C6C'"
        >
          <SuccessFilled v-if="migrationResult.success && validationErrors.length === 0" />
          <CircleCloseFilled v-else />
        </el-icon>
      </div>
      
      <h3 v-if="migrationResult.success && validationErrors.length === 0">迁移完成！</h3>
      <h3 v-else-if="validationErrors.length > 0">数据验证失败</h3>
      <h3 v-else>迁移失败</h3>
      
      <p v-if="migrationResult.success && validationErrors.length === 0" class="result-message">
        成功迁移了 {{ migrationResult.migratedCount }} 个智能体到服务器，本地数据已清理
      </p>
      <p v-else-if="validationErrors.length > 0" class="result-message">
        迁移过程中发现数据完整性问题
      </p>
      <p v-else class="result-message">{{ migrationResult.message }}</p>
      
      <!-- 验证错误详情 -->
      <div v-if="validationErrors.length > 0" class="error-details">
        <el-collapse>
          <el-collapse-item title="查看验证错误详情" name="validation-errors">
            <ul class="error-list">
              <li v-for="(error, index) in validationErrors" :key="index">
                {{ error }}
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <!-- 迁移错误详情 -->
      <div v-if="migrationResult.errors.length > 0" class="error-details">
        <el-collapse>
          <el-collapse-item title="查看错误详情" name="errors">
            <ul class="error-list">
              <li v-for="(error, index) in migrationResult.errors" :key="index">
                {{ error }}
              </li>
            </ul>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <!-- 迁移前按钮 -->
        <template v-if="!migrating && !isValidating && !migrationCompleted">
          <el-button @click="skipMigration">跳过</el-button>
          <el-button type="primary" @click="startMigration">开始迁移</el-button>
        </template>
        
        <!-- 迁移完成后按钮 -->
        <template v-if="migrationCompleted">
          <el-button 
            v-if="!migrationResult.success || validationErrors.length > 0" 
            @click="retryMigration"
          >
            重试
          </el-button>
          <el-button type="primary" @click="closeMigration">确定</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Upload, 
  Loading, 
  SuccessFilled, 
  CircleCloseFilled 
} from '@element-plus/icons-vue'
import { 
  migrateData, 
  cleanupLocalStorageData,
  validateMigrationData,
  type MigrationResult 
} from '../services/migrationService'

/**
 * 组件属性
 */
interface Props {
  /** 对话框是否可见 */
  modelValue: boolean
  /** 需要迁移的数据数量 */
  dataCount: number
}

/**
 * 组件事件
 */
interface Emits {
  /** 更新可见状态 */
  'update:modelValue': [value: boolean]
  /** 迁移完成事件 */
  'migration-completed': [result: MigrationResult]
  /** 跳过迁移事件 */
  'migration-skipped': []
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

/** 对话框可见状态 */
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

/** 迁移状态 */
const migrating = ref(false)
const migrationCompleted = ref(false)
const migratedCount = ref(0)
const totalCount = ref(0)
const currentMigrationItem = ref('')
const isValidating = ref(false)
const validationErrors = ref<string[]>([])
const migrationResult = ref<MigrationResult>({
  success: false,
  migratedCount: 0,
  failedCount: 0,
  errors: [],
  message: ''
})

/** 迁移进度百分比 */
const migrationPercentage = computed(() => {
  if (totalCount.value === 0) return 0
  return Math.round((migratedCount.value / totalCount.value) * 100)
})

/**
 * 开始迁移
 */
async function startMigration() {
  try {
    migrating.value = true
    migrationCompleted.value = false
    migratedCount.value = 0
    totalCount.value = props.dataCount
    currentMigrationItem.value = '准备迁移...'
    validationErrors.value = []

    // 执行迁移
    const result = await migrateData((current, total, agentName) => {
      migratedCount.value = current - 1 // 减1因为是正在处理的项目
      totalCount.value = total
      currentMigrationItem.value = `正在迁移: ${agentName}`
    })

    // 更新最终结果
    migrationResult.value = result
    migrating.value = false

    // 如果迁移成功，进行数据验证
    if (result.success) {
      await validateMigrationResult(result)
      
      if (validationErrors.value.length === 0) {
        migrationCompleted.value = true
        // 验证通过后清理localStorage
        await cleanupLocalStorage()
        ElMessage.success('数据迁移成功！')
      } else {
        ElMessage.error('数据验证失败，请查看详情')
      }
    } else {
      migrationCompleted.value = true
      ElMessage.error('数据迁移失败，请查看详情')
    }

    // 触发迁移完成事件
    emit('migration-completed', result)

  } catch (error) {
    migrating.value = false
    migrationCompleted.value = true
    
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    migrationResult.value = {
      success: false,
      migratedCount: 0,
      failedCount: props.dataCount,
      errors: [errorMessage],
      message: '迁移过程中发生错误'
    }

    ElMessage.error('迁移失败: ' + errorMessage)
    emit('migration-completed', migrationResult.value)
  }
}

/**
 * 重试迁移
 */
function retryMigration() {
  migrationCompleted.value = false
  startMigration()
}

/**
 * 验证迁移结果
 */
async function validateMigrationResult(result: MigrationResult) {
  try {
    isValidating.value = true
    currentMigrationItem.value = '正在验证数据...'
    
    // 获取原始数据进行验证
    const originalDataStr = localStorage.getItem('agents')
    if (originalDataStr && result.migratedAgentIds) {
      const originalAgents = JSON.parse(originalDataStr)
      const validation = await validateMigrationData(originalAgents, result.migratedAgentIds)
      
      if (!validation.isValid) {
        validationErrors.value = validation.errors
        console.warn('数据验证失败:', validation.errors)
      } else {
        console.log('数据验证通过')
      }
    }
  } catch (error) {
    console.error('验证过程发生错误:', error)
    validationErrors.value.push('验证过程发生错误: ' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    isValidating.value = false
  }
}

/**
 * 清理localStorage中的数据
 */
async function cleanupLocalStorage() {
  try {
    // 清理智能体数据
    localStorage.removeItem('agents')
    
    // 标记迁移已完成
    localStorage.setItem('migration_completed', 'true')
    
    console.log('localStorage清理完成')
  } catch (error) {
    console.error('清理localStorage失败:', error)
  }
}

/**
 * 跳过迁移
 */
function skipMigration() {
  visible.value = false
  emit('migration-skipped')
  ElMessage.info('已跳过数据迁移')
}

/**
 * 关闭迁移对话框
 */
function closeMigration() {
  visible.value = false
}
</script>

<style scoped>
.migration-prompt,
.migration-progress,
.migration-result {
  text-align: center;
  padding: 20px 0;
}

.icon-container {
  margin-bottom: 16px;
}

.rotating {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

h3 {
  margin: 16px 0 8px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.description {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 20px;
}

.benefits {
  text-align: left;
  background: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin-top: 16px;
}

.benefits h4 {
  margin: 0 0 8px 0;
  color: #409EFF;
  font-size: 14px;
}

.benefits ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  font-size: 14px;
}

.benefits li {
  margin-bottom: 4px;
}

.current-item {
  color: #409EFF;
  font-weight: 500;
  margin: 16px 0;
  min-height: 20px;
}

.progress-info {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
}

.result-message {
  color: #606266;
  margin: 16px 0;
}

.error-details {
  margin-top: 16px;
  text-align: left;
}

.error-list {
  margin: 0;
  padding-left: 20px;
  color: #F56C6C;
  font-size: 14px;
}

.error-list li {
  margin-bottom: 8px;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 8px;
}
</style>